package GUI.service.impl;

import GUI.dao.BaseDAO;
import GUI.dao.UserDAO;
import GUI.dao.impl.UserDAOImpl;
import GUI.pojo.UserDO;
import GUI.service.UserService;

public class UserServiceImpl extends BaseDAO implements UserService {
private UserDAO userDAO=new UserDAOImpl();
    //登录
    @Override
    public UserDO getByUsernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username,pwd);
    }
    //存款
    @Override
    public void saveMoney(int id, double balance) {
        UserDO user =userDAO.getById(id);
        user.setBalance(user.getBalance()+balance);
        userDAO.update(user);
    }
   //取款
    @Override
    public void getMoney(int id, double balance) throws Exception {
        UserDO user =userDAO.getById(id);
        if(user.getBalance()<balance){
            throw new Exception("余额不足");
        }
        user.setBalance(user.getBalance()-balance);
        userDAO.update(user);
    }
   //查询
    @Override
    public double searchMoney(int id) {
        UserDO user=userDAO.getById(id);
        userDAO.update(user);
        return user.getBalance();
    }

    //转账
    @Override
    public void transferMoney(String username, String othername, double balance) throws Exception {
        UserDO loginuser=userDAO.getByUsername(username);
        UserDO otheruser=userDAO.getByUsername(othername);
        // 判断账号是否存在
        if (otheruser == null) {
            throw new Exception("查无此人");
        }
        // 判断是否转给自己
        if (loginuser.getAccount().equals(otheruser)) {
            throw new Exception("不能转给自己");
        }
        // 判断余额是否足够
        if (balance > loginuser.getBalance()) {
            throw new Exception("余额不足");
        }
        //扣钱
        loginuser.setBalance(loginuser.getBalance()-balance);
        //加钱
        otheruser.setBalance(otheruser.getBalance()+balance);
        try {
            getConnection();
            setAutoCommit(false);
            userDAO.update(loginuser);
            userDAO.update(otheruser);
            commit();
        } catch (Exception e1) {
            rollback();
            throw new Exception("转账失败");
        } finally {
            close();
        }
    }
    //改密
    @Override
    public void setPwd(String username, String oldPwd, String newPwd) throws Exception {
        UserDO user=userDAO.getByUsername(username);
        if(oldPwd.equals(newPwd)){
            user.setPwd(newPwd);
            userDAO.update(user);
        }else {
            throw new Exception("两次密码输入不正确");
        }
    }




}
